package com.baoyouqun.API.sms;

import com.alibaba.fastjson2.JSON;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendBatchSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendBatchSmsResponse;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Component
public class AliyunSmsClient {

    private final Client client;
    private final SmsProperties smsProperties;

    @Autowired
    public AliyunSmsClient(SmsProperties smsProperties) throws Exception {
        this.smsProperties = smsProperties;
        // 初始化阿里云客户端
        Config config = new Config().setAccessKeyId(smsProperties.getAccessKeyId()).setAccessKeySecret(smsProperties.getAccessKeySecret());
        config.endpoint = "dysmsapi.aliyuncs.com";
        this.client = new Client(config);
    }

    /**
     * 发送短信验证码
     *
     * @param phone         手机号
     * @param code          验证码
     * @param expireMinutes 有效期(分钟)
     * @return 是否发送成功
     * @throws Exception 发送异常
     */
    public boolean sendVerificationCode(String phone, String code, int expireMinutes) throws Exception {
        SendSmsRequest request = new SendSmsRequest().setPhoneNumbers(phone).setSignName(smsProperties.getSignName()).setTemplateCode(smsProperties.getTemplateCode()).setTemplateParam("{\"code\":\"" + code + "\", \"expire\":\"" + expireMinutes + "\"}");

        SendSmsResponse response = client.sendSms(request);
        return "OK".equals(response.getBody().getCode());
    }


    /**
     * 批量发送模板短信（阿里云SendBatchSms接口实现）
     *
     * @param phoneNumbers   手机号列表（单次最多100个）
     * @param signNames      签名列表（需与手机号数量一致）
     * @param templateCode   模板ID
     * @param templateParams 模板参数列表（需与手机号数量一致，可为null）
     * @return 发送结果（包含bizId和是否成功）
     * @throws Exception 发送异常
     */
    public BatchSmsResult sendBatchSms(
            List<String> phoneNumbers,
            List<String> signNames,
            String templateCode,
            List<Map<String, String>> templateParams) throws Exception {

        // 验证参数数量一致性
        if (phoneNumbers.size() > 100) {
            throw new IllegalArgumentException("单次批量发送最多支持100个手机号");
        }

        // 转换参数为JSON字符串
        String phoneNumberJson = JSON.toJSONString(phoneNumbers);
        String signNameJson = JSON.toJSONString(signNames);
        String templateParamJson = templateParams != null ? JSON.toJSONString(templateParams) : null;

        // 构建请求
        SendBatchSmsRequest request = new SendBatchSmsRequest()
                .setPhoneNumberJson(phoneNumberJson)
                .setSignNameJson(signNameJson)
                .setTemplateCode(templateCode)
                .setTemplateParamJson(templateParamJson);

        // 调用阿里云接口
        SendBatchSmsResponse response = client.sendBatchSms(request);

        // 封装结果
        return new BatchSmsResult(
                "OK".equals(response.getBody().getCode()),
                response.getBody().getBizId(),
                response.getBody().getMessage()
        );
    }

    // 批量发送结果封装类
    public static class BatchSmsResult {
        private final boolean success;
        private final String bizId; // 发送回执ID，可用于查询发送详情
        private final String message; // 响应信息

        public BatchSmsResult(boolean success, String bizId, String message) {
            this.success = success;
            this.bizId = bizId;
            this.message = message;
        }

        // getter方法
        public boolean isSuccess() {
            return success;
        }

        public String getBizId() {
            return bizId;
        }

        public String getMessage() {
            return message;
        }
    }
}
